package models

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/natefinch/lumberjack"
	"github.com/xormplus/xorm"
	"github.com/xormplus/xorm/log"
	"github.com/zw2582/ginlib"
)

var (
	DB *xorm.Engine
)

//InitDb 初始化数据库
func InitDb() *xorm.Engine {
	host := ginlib.Ini_Str("mysql.host")
	name := ginlib.Ini_Str("mysql.name")
	password := ginlib.Ini_Str("mysql.password")
	database := ginlib.Ini_Str("mysql.database")
	eng, err := xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8", name, password, host, database))
	if err != nil {
		panic(err)
	}
	DB = eng
	//DB.SetTZLocation(time.LoadLocation())

	//设置日志
	hook := lumberjack.Logger{
		Filename:   "./logs/sql.log",  //日志文件路径
		MaxSize:    128, //最大字节
		MaxAge:     30,
		MaxBackups: 7,
		Compress:   true,
	}
	logger := log.NewSimpleLogger(&hook)

	//设置日志等级
	DB.SetLogger(logger)
	DB.SetLogLevel(log.LOG_DEBUG)
	showSql := ginlib.Ini_Bool("mysql.show_sql", true)
	DB.ShowSQL(showSql)

	return DB
}
